<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElCheckbox, ElForm, ElFormItem, ElInput, ElMessage, ElTooltip } from 'element-plus';
import { userLoginApi } from '@/apis/api-user';
import { delLocal, getBrowserLocation, getLocal, setLocal } from '@/common/common-helper';
import ReImageVerify from '@/components/ReImageVerify';
import SvgIconIndex from '@/components/SvgIconIndex.vue';
import { useSystemStore, useUserStore } from '@/stores';
import { USER_KEY_TOKEN_REMEMBER, setToken } from '@/utils/auth';

const router = useRouter();
const userStore = useUserStore();
const systemStore = useSystemStore();

const loginFormRef = ref(); // 登录表单ref
const isCapslock = ref(false); // 是否大写锁定
const imgCode = ref('');
const loading = ref(false); // 按钮loading
const verifyRef = ref(null);
const remember_password = ref(false);

const loginData = ref({
  username: '',
  password: '',
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入用户名',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入密码',
      },
      {
        min: 6,
        message: '密码不能少于6位',
        trigger: 'blur',
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入验证码',
      },
    ],
  };
});

onMounted(() => {
  if (getLocal(USER_KEY_TOKEN_REMEMBER) == null) {
    remember_password.value = false;
    loginData.value.username = '';
    loginData.value.password = '';
  } else {
    remember_password.value = true;

    const userVal = getLocal(USER_KEY_TOKEN_REMEMBER);

    loginData.value.username = userVal.u;
    loginData.value.password = userVal.p;
  }
});

/** 检查输入大小写 */
const checkCapslock = (event) => {
  // 防止浏览器密码自动填充时报错
  if (event) {
    isCapslock.value = event.getModifierState('CapsLock');
  }
};

// 记住密码
const onChangeRemember = (e) => {
  remember_password.value = e;

  if (!e) {
    delLocal(USER_KEY_TOKEN_REMEMBER);
  }
};

// 判断是否记住密码
const determineRememberPass = (password) => {
  if (remember_password.value) {
    setLocal(USER_KEY_TOKEN_REMEMBER, password);
  } else {
    delLocal(USER_KEY_TOKEN_REMEMBER);
  }
};

const handleLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true;

      if (loginData.value.captchaCode !== imgCode.value) {
        ElMessage.warning('验证码不正确');
        loading.value = false;
        loginData.value.captchaCode = '';
        verifyRef.value.getImgCode();

        return;
      }

      determineRememberPass({
        p: loginData.value.password,
        u: loginData.value.username,
      });

      const [err, data] = await userLoginApi({
        username: loginData.value.username,
        password: loginData.value.password,
      });

      if (!err) {
        const { accessToken, expireIn } = data.data;

        localStorage.setItem(
          'tokenInfo',
          JSON.stringify({
            ...data.data,
            expireTime: Date.now() + expireIn,
          }),
        );
        setToken(accessToken, true);
        router.replace('/launch');
        getBrowserLocation();
        systemStore.getSystemPermissionAllApi();
        systemStore.getSystemDeptAllApi();
        systemStore.getSystemRoleAllApi();
        setTimeout(() => {
          userStore.SELECT_LOGIN_CURRENT();
        });
        loading.value = false;
      } else {
        loginData.value.captchaCode = '';
        verifyRef.value.getImgCode();
        loading.value = false;
      }
    }

    loading.value = false;
  });
};
</script>
<template>
  <div class="login-container flex-center">
    <div class="login-content flex">
      <div class="login-left" />
      <div class="login-right">
        <p>欢迎登录</p>
        <p>林业综合管理平台</p>

        <div class="mt-61px">
          <ElForm ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
            <!-- 用户名 -->
            <ElFormItem prop="username">
              <div class="w-full flex-y-center">
                <SvgIconIndex icon-class="user" class="mx-2" size="17px" color="#999999" />
                <ElInput
                  ref="username"
                  v-model.trim="loginData.username"
                  placeholder="请输入用户名"
                  name="username"
                  size="large"
                  class="h-[52px] pt-1"
                />
              </div>
            </ElFormItem>

            <!-- 密码 -->
            <ElTooltip :visible="isCapslock" :content="'大写锁定已打开'" placement="right">
              <ElFormItem prop="password">
                <div class="w-full flex-y-center">
                  <SvgIconIndex icon-class="lock" class="mx-2" size="17px" color="#999999" />
                  <ElInput
                    v-model.trim="loginData.password"
                    placeholder="请输入密码"
                    type="password"
                    name="password"
                    size="large"
                    class="h-[52px] pr-2 pt-1"
                    show-password
                    @keyup="checkCapslock"
                    @keyup.enter="handleLogin"
                  />
                </div>
              </ElFormItem>
            </ElTooltip>

            <!-- 验证码 -->
            <ElFormItem prop="captchaCode">
              <div class="w-full flex-y-center">
                <SvgIconIndex icon-class="captcha" class="mx-2" size="17px" color="#999999" />
                <ElInput
                  v-model.trim="loginData.captchaCode"
                  auto-complete="off"
                  size="large"
                  class="h-[52px] flex-1 pt-1"
                  placeholder="请输入验证码"
                  maxlength="4"
                  @keyup.enter="handleLogin"
                >
                  <template #append>
                    <ReImageVerify ref="verifyRef" v-model:code="imgCode" />
                  </template>
                </ElInput>
              </div>
            </ElFormItem>
            <!-- 记住密码 -->
            <div class="remember">
              <ElCheckbox
                v-model="remember_password"
                label="记住密码"
                size="large"
                @change="(e) => onChangeRemember(e)"
              />
            </div>

            <!-- 登录按钮 -->
            <ElButton
              :loading="loading"
              type="primary"
              size="large"
              class="mt-130px h-49px w-full"
              @click.prevent="handleLogin"
              >登录
            </ElButton>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  background-image: url('../../assets/images/login/登录背景.png');
  background-size: 100% 100%;

  .login-content {
    width: 1380px;
    height: 720px;
    background: #ffffff;

    .login-left {
      width: 860px;
      height: 100%;
      background-image: url('../../assets/images/login/图片.png');
      background-size: 100% 100%;
    }

    .login-right {
      width: calc(100% - 860px);
      height: 100%;
      padding: 65px 51px 64px 44px;
      p {
        margin: 0;
        color: #333333;
        font-size: 34px;
        font-family: FZDaHei-B02S, FZDaHei-B02S-Regular;
        letter-spacing: 1.02px;
        &:first-child {
          margin-bottom: 16px;
        }
      }

      .remember {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 15px;

        :deep(.el-checkbox__label) {
          font-size: 16px;
        }

        :deep(.el-checkbox__inner) {
          width: 18px;
          height: 18px;
        }

        :deep(.el-checkbox__inner::after) {
          top: 3px;
          left: 6px;
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 20px;
        background: $input-background;
        border-radius: 5px;
      }

      :deep(.el-input) {
        .el-input__wrapper {
          padding: 0;
          font-size: 18px;
          background-color: transparent;
          box-shadow: none;

          &.is-focus,
          &:hover {
            box-shadow: none !important;
          }

          input:-webkit-autofill {
            transition: background-color 1000s ease-in-out 0s;
          }
        }
      }

      :deep(.el-input-group__append) {
        padding: 0;
        background: $input-background;
        box-shadow: none;
      }

      :deep(.el-button--primary) {
        height: 49px;
        font-size: 18px;
      }
    }
  }
}
</style>
